package com.tyl.xtk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tyl.xtk.beans.po.FileInfo;
import com.tyl.xtk.mapper.FileInfoMapper;
import com.tyl.xtk.service.FileInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 文件信息服务实现类
 */
@Slf4j
@Service
public class FileInfoServiceImpl extends DataServiceImpl<FileInfoMapper, FileInfo> implements FileInfoService {

    @Value("${spring.file.storage-path}")
    private String storagePath;


    @Override
    public boolean deleteFilesBefore(LocalDateTime cutoffTime) {
        LambdaQueryWrapper<FileInfo> wrapper = new LambdaQueryWrapper<FileInfo>()
                .lt(FileInfo::getUpdateTime, cutoffTime);
        // 逻辑删除
        return baseMapper.delete(wrapper) > 0;
    }

    @Override
    public boolean realDeleteBefore(LocalDateTime time) {
        // 先查询出所有需要真实删除的文件
        LambdaQueryWrapper<FileInfo> queryWrapper = new LambdaQueryWrapper<FileInfo>()
                .eq(FileInfo::getDeleted, true)
                .lt(FileInfo::getUpdateTime, time);
        List<FileInfo> filesToDelete = baseMapper.selectList(queryWrapper);

        // 删除文件系统中的文件
        for (FileInfo file : filesToDelete) {
            try {
                String filePath = storagePath + File.separator + file.getId();
                Path path = Paths.get(filePath);
                if (Files.exists(path)) {
                    Files.delete(path);
                }
            } catch (IOException e) {
                // 记录错误但继续处理其他文件
                log.error("文件删除失败：{}", e.getMessage());
            }
        }

        // 从数据库中删除记录
        return baseMapper.delete(queryWrapper) > 0;
    }
}